import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;

import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

public class TccPropertySourceSpringBoot15x extends BaseTccPropertySource {
    private final PropertySourceLoader loader;

    protected TccPropertySourceSpringBoot15x(
            TccPlusProperties.TccConfig tcc, PropertySourceLoader loader
    ) {
        super(tcc.getPsm(), tcc.getConfigSpace(), tcc.getEnv(), tcc.getKey());
        this.loader = loader;
    }

    @Override
    protected Properties loadProperties(String config) throws IOException {
        PropertySource<?> loaded = loader.load(getName(), new StringResource(config), null);
        Properties props = new Properties();
        if (!(loaded instanceof EnumerablePropertySource)) {
            return props;
        }
        for (String propertyName : ((EnumerablePropertySource<?>) loaded).getPropertyNames()) {
            props.put(propertyName, Objects.requireNonNull(loaded.getProperty(propertyName)));
        }
        return props;
    }
}
